<template>
	<div>
		<el-form class="query-form" :model="query_params">
			<el-row>
		    <el-col class="query-item" :span="6">
					<el-form-item label="卡券名称" prop="name">
						<el-input v-model="query_params.name" placeholder="请输入卡券名称" autocomplete="off" />
					</el-form-item>
				</el-col>
				<el-col class="query-item" :span="6">
					<el-form-item >
						<el-button type="primary" @click="search">搜索</el-button>
					</el-form-item>
				</el-col>

		  </el-row>
		</el-form>
		<el-row class="add-box-css"><el-button type="primary" @click="info_operation()">新增</el-button></el-row>
		<el-table :data="tableData" border style="width: 100%">
		    <el-table-column label="序号" width="180" >
				<template #default="scope">
		            {{scope.$index+1}}
		        </template>
		    </el-table-column>
		    <el-table-column prop="name" label="卡券名称" width="180" />
				<el-table-column prop="activity_name" label="所属活动" width="180" />
		    <el-table-column prop="content" label="服务内容" >
					<template v-slot:default="scope">
								{{getServideNum(scope.row)}}
					</template>
				</el-table-column>
				<el-table-column prop="amount" label="使用次数" width="180" />
		    <el-table-column prop="createdAt" label="创建时间" />
				<el-table-column prop="disable" label="状态" >
					<template #default="scope">
							{{getStatus(scope.row)}}
					</template>
				</el-table-column>
		    <!-- <el-table-column  label="激活" >
		    	<template #default="scope">
		    		<el-switch  v-model="scope.row.disable" @click="confirm(scope.row)"/>
		      </template>
				</el-table-column> -->
				<el-table-column  label="操作" >
		    	<template #default="scope">
		    		<el-button type="primary" size="small" @click="info_operation(scope.row)">编辑</el-button>
		      </template>
				</el-table-column>
		</el-table>
		<div class="pagination_box">
			<el-pagination background layout="prev, pager, next"  :total="total" @current-change="handleCurrentChange" />
		</div>
		<!-- 新增 & 编辑 -->
		<div>
			<el-drawer v-model="drawer" size='60%' :with-header="true">
					<template #title>
						<h4>新增/编辑 卡券</h4>
					</template>
			    <template #default>
			      <div>
							<el-form
							    ref="ruleFormRef"
							    :model="ruleForm"
							    status-icon
							    :rules="rules"
							    label-width="120px"
							    class="demo-ruleForm"
							    :loading="loading"
							  >
							    <el-form-item label="卡券名称" prop="name">
							      <el-input v-model="ruleForm.name"  autocomplete="off" />
							    </el-form-item>
							    <el-form-item label="服务项目" prop="services" :rules="[
						        { required: true, message: '请选择服务项目',trigger: 'blur' }
						      ]">
							      <!-- <el-input v-model="ruleForm.content"  autocomplete="off" /> -->
										<el-select
								      v-model="ruleForm.services"
								      multiple
								      placeholder="请选择服务内容"
								      style="width: 240px"
								    >
								      <el-option
								        v-for="item in service_items"
								        :key="item.id"
								        :label="item.name"
								        :value="item.id"
								      />
								    </el-select>
							    </el-form-item>
									<el-form-item label="所属活动" prop="activity" :rules="[
						        { required: true, message: '请选择所属活动',trigger: 'blur' }
						      ]">
										<el-select v-model="ruleForm.activity" class="m-2" placeholder="请选择所属活动">
									    <el-option
									      v-for="item in activityList"
									      :key="item.id"
									      :label="item.name"
									      :value="item.id"
									    />
									  </el-select>
									</el-form-item>
									<el-form-item label="卡券图片" prop="headImg">
								     <el-upload
											    v-model:file-list="coupon_headImg"
											    :action="action"
											    :auto-upload="true"
											    list-type="picture-card"
											    :on-preview="handlePictureCardPreview"
											    :on-remove="handleRemove"
											    :on-change="handleChange(0,'coupon_headImg')"
											    :http-request="uploadAction"
											  >
										    <el-icon><Plus /></el-icon>
										 </el-upload>
									</el-form-item>
									<el-form-item label="卡券说明" prop="desc">
							      <el-input v-model="ruleForm.desc" type="textarea"  autocomplete="off" />
							    </el-form-item>
									<el-form-item label="卡券价格" prop="price">
							      <el-input v-model.number="ruleForm.price"  autocomplete="off" />
							    </el-form-item>
									<el-form-item label="服务次数" prop="count">
							      <el-input v-model="ruleForm.count"  autocomplete="off" />
							    </el-form-item>
									<el-form-item label="是否禁用" prop="disable">
							      <el-switch v-model="ruleForm.disable" />
							    </el-form-item>
							    <el-form-item >
							      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
							    </el-form-item>
							</el-form>
			      </div>
			    </template>
			  </el-drawer>
		</div>
		<!-- 图片预览 -->
		<el-dialog v-model="dialogVisible">
	    <img w-full :src="dialogImageUrl" alt="Preview Image" />
	  </el-dialog>
	</div>
</template>
<script type="text/javascript">
	import {  ElMessageBox ,ElMessage,FormInstance,FormRules } from 'element-plus'
	export default {
		data(){
			return {
				action:'',
				queryForm:{},
				query_params:{
					current:1,
					size:10
				},
				tableData:[],
				total:0,
				drawer:false,
				// 表单
				ruleFormRef:{},
				ruleForm :{},
				rules:{
				  name: [
				    { required: true, message: '请输入卡券名称', trigger: 'blur' },
				  ],
					price: [
				    { required: true, message: '请输入卡券名称', trigger: 'blur' },
						{ type: 'number', message: '卡券价格必须是数字' },
				  ],
				},
				//服务列表
				services:'',
				service_items:[],
				//活动列表
				activity:'',
				activityList:[],
				//卡券图片
				headImg:[],
				loading:false,
				list_type:'',
				//卡券图片
				coupon_headImg:[],
				//预览图片
				dialogVisible:false,
				dialogImageUrl:'',//预览地址,
			}
		},
		methods:{
			submitForm(val){//提交
				// console.log(val);
				console.log(this.ruleForm);
			},
			search(){
				this.query_params.current=1;
				this.query_params.current=10;
				// console.log(this.queryForm);
				this.getList()
			},
			info_operation(row){//编辑 & 新增 服务
				//清空选项
				this.services='';
				this.activity="";
				//打开面板
				this.drawer=true
				// console.log(row);
				if(row){//编辑
						// 填充值
						for(let prop in row){
							let num_arr=["price"];//数字化
							if(num_arr.includes(prop)){
									row[prop]=parseFloat(row[prop])
							}
							this.ruleForm[prop]=row[prop];
						}
						let services=[];
						for(let item of row.service){
							services.push(item.id)
						}
						this.ruleForm.services=services;//服务项目
						this.ruleForm.activity=this.ruleForm.activity_id;//所属活动
						//梳理文件数据
						this.cardDataEdit(row)
				}
				else{//新增
					this.ruleForm={};
					//清除所有文件数组
					this.clearFiles()
				}
				// console.log(this.ruleForm);
			},
			clearFiles(){
				const fields=['headImg'];//文件字段名
				var prefix="coupon_";//前缀
				for(let val of fields){
					let name=prefix+val
					this[name]=[];
				}
			},
			cardDataEdit(row){//梳理文件数据
				const fields=['headImg'];//文件名
				var prefix="coupon_";
				for(let prop of fields){
					let name=prefix+prop;
					this[name]=[];
					if(row[prop]){
						var activity_obj = row[prop].split(",");
						var new_list=[];
						for (let val of activity_obj){
								let new_img = {
										content: val,
										url: val
								}
								new_list.push(new_img)
						}
						this[name] = new_list;
					}
				}
			},
			getServideNum(row){
				// console.log(row);
				return `共${row.service.length}条服务`
			},
			getStatus(row){//查询状态
				// console.log(row);
				var str="正常"
				if(!row.disable){
					str="已禁止"
				}
				return str
			},
			handleCurrentChange(val){//分页
				// console.log(val)
				this.query_params.current=val;
				this.getList();
			},
			getList(){//获取卡券列表
				this.$API.getCouponList(this.query_params).then(res=>{
					// console.log(res)
					if(res.code==200){
						this.tableData=res.data;
						if(this.total<1){
							this.total=res.total
						}
						//headImg
            // if (res.data.headImg){
            //     var headImgs = this.ruleForm.headImg.split(",");
            //     var new_logo_list=[];
            //     for (let val of headImgs){
            //         let new_img = {
            //             content: val,
            //             url: val
            //         }
            //         new_logo_list.push(new_img)
            //     }
            //     this.headImg = new_logo_list;
            // }
						//获取服务列表
						this.$API.getServiceList({}).then(res=>{
								this.service_items=res.data
						})
						//获取活动列表
						this.$API.getActivityList({}).then(res=>{
								this.activityList=res.data
						})
					}
				})
			},
			//图片上传
			handlePictureCardPreview(uploadFile){//预览文件
				this.dialogImageUrl=uploadFile.url
				this.dialogVisible=true
			},
			handleRemove(uploadFile, uploadFiles){

			},
			handleChange(i,type){
				this.list_type=type
				// if(type=='normsList'){
				// 	this.current_norms=i
				// }
			},
			async uploadAction(file){//文件上传
					// console.log(file);
					file.status = 'uploading';
					file.message = '上传中...';
					//开始上传
					const content = new FormData();
					//上传图片需要转换二进制这里要用到FormData
					content.append("file", file.file);
					const res=await this.$API.upload(content);
					if(res.code==200){
						file.status = 'done';
						file.message = '上传成功';
						file.url = res.data;
					}
					else{
						file.status = 'failed';
						file.message = '上传失败';
					}
					//重新赋值  img/视频
					for(let item of this[this.list_type]){
						if(item.uid==file.file.uid){
							item.url=file.url
						}
					}
			},
		},
		mounted(){
			this.getList();
			// console.log(FormInstance,FormRules );
		}
	}
</script>
<style type="text/css">
	.pagination_box{
		    text-align: center;
		    display: flex;
		    justify-content: center;
		    width: 100%;
	}
	.query-item{
		margin-right:10px
	}
	.query-form{
		    padding:20px;
				    padding-bottom: 0px;
	}
	.add-box-css{
		width:100%;
		align-items: end;
    justify-content: end;
    padding: 0px 1rem 1rem 0px;
	}
</style>
